<?php

namespace app\report\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class MonthlyProfitLogic
{

    public function __construct()
    {
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $shop_id = $params['shop_id'] ?? '';
        $limit = $params['limit'] ?? 10;
        
        $date = $params['date'] ?? [];

        $where = [];

        if(!empty($date)){
            $where[]  = ['date', '>=', $date[0]];
            $where[]  = ['date', '<=', $date[1]];
        }
        

        if(!empty($shop_id)){
            $where['shop_id'] = $shop_id;
        }
        $where[] = ['total_price_old','>',0];

        $list = Db::name('report_monthly_profit')
            ->alias('a')
            ->where($where)
            ->order("date desc,total_price_old desc")
            ->paginate($limit);

        $lists = $list->items();
        // foreach ($lists as $k=>$v) {
        //     if(!empty($v['createtime'])){
        //         $lists[$k]['createtime'] = date('Y-m-d',$v['createtime']);
        //         if(!empty($v['updatetime'])){
        //             $lists[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
        //         }else{
        //             $lists[$k]['updatetime'] = "至今";
        //         }
        //     }else{
        //         $lists[$k]['createtime'] = "";
        //         $lists[$k]['updatetime'] = "";
        //     }
        // }

        $spends_profit = Db::name('report_monthly_profit')
            ->field('
                SUM(total_price_old) as total_price_old,
                SUM(count) as count,
                SUM(total_price) as total_price,
                SUM(count_LogisticsMarkupFee) as count_LogisticsMarkupFee,
                SUM(skuquantity) as skuquantity,
                SUM(freight) as freight,
                SUM(material) as material,
                SUM(dispute) as dispute,
                SUM(LogisticsMarkupFee) as LogisticsMarkupFee
            ')
            ->where($where)
            ->select()->toarray();
            $spends = $spends_profit[0];
                
        $data = [
            'list' => $lists,
            'total' => $list->total(),
            'spends' => $spends,
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $header = [];
        $header[] = ['订单号', 'name'];
        $header[] = ['支付状态', 'financial_status'];
        $header[] = ['物流状态', 'fulfillment_status'];
        $header[] = ['现销售额$', 'total_price'];
        $header[] = ['账单物流成本￥', 'freight'];
        $header[] = ['预估物流成本￥', 'estimate_freight'];
        $header[] = ['采购成本￥', 'material'];
        $header[] = ['争议成本$', 'dispute'];
        $header[] = ['退款$', 'refund'];
        $header[] = ['物流单号', 'tracking_number'];
        $header[] = ['币种', 'currency'];
        $header[] = ['件数', 'skuquantity'];
        $header[] = ['物流匹配状态', 'freight_status'];
        $header[] = ['采购匹配状态', 'material_status'];
        $header[] = ['争议类型', 'disputeapi_type'];
        $header[] = ['争议状态', 'disputeapi_status'];
        
        $tableName = "report_monthly_profit";
        $fileName = "export_" . $tableName . "_" . time();

        $where = [];
        //id参数
        $id = $params['id'] ?? '';
        $report_monthly_personal = Db::name('report_monthly_profit')->where('id',$id)->find();
        if(empty($report_monthly_personal)){
            return json(DefaultResponse(200, true, '暂无数据'));
        }
        $date = $report_monthly_personal['date'];

        $start_time = strtotime($date);
        $end_time = strtotime("+1 month", strtotime($date . "-01"));  
        $where[]  = ['createtime', '>=', $start_time];
        $where[]  = ['createtime', '<=', $end_time]; 
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $where[]  = ['shop_id', '=', $report_monthly_personal['shop_id']];

        $count = Db::name('order_achievement')
            ->where($where)
            ->count();
        if($count >= 5000){
            return '数据超过5000条,异步下载中，请2分钟后前往【任务组管理/系统导出管理】页面下载';
        }
        
        $lists = Db::name('order_achievement')
            ->field('
                name,
                financial_status,
                fulfillment_status,
                tracking_number,
                currency,
                freight,
                estimate_freight,
                material,
                dispute,
                total_price,
                skuquantity,
                freight_status,
                material_status,
                disputeapi_type,
                disputeapi_status,
                refund
            ')
            ->where($where)
            ->select()->toarray();
        
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }
}
